﻿using CIS.Client.Common.HttpRequestHelper;
using CIS.Client.Modules.Operation.Models;
using CIS.Common.Dtos.ClientDtos;
using CIS.Common.Dtos.CommandDtos;
using CIS.Common.Entitys;
using CIS.Common.Enums;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CIS.Client.Modules.Operation.ViewModels
{
    public class CassetteMapDownloadViewModel : BindableBase, IDialogAware
    {
        private HttpRequestClient? _httpRequest;
        private readonly IDialogService _dialogService;

        public CassetteMapDownloadViewModel(HttpRequestClient httpRequest,IDialogService dialogService)
        {
            _httpRequest= httpRequest;
            this._dialogService = dialogService;
            PPIDs = new List<string>();
        }

        #region 属性
        private PortModel port;
        /// <summary>
        /// 当前要下账的Port
        /// </summary>
        public PortModel Port
        {
            get { return port; }
            set { port = value; }
        }

        private JobModel selectSlot;
        /// <summary>
        /// 选中的层的玻璃信息
        /// </summary>
        public JobModel SelectSlot
        {
            get { return selectSlot; }
            set
            {
                selectSlot = value;
                GetSelectSlot();
            }
        }

        private string selectedPPID;
        /// <summary>
        /// 选中的PPID 作用与所有选中的层的玻璃信息的 PPID
        /// </summary>
        public string SelectedPPID
        {
            get { return selectedPPID; }
            set
            {
                selectedPPID = value;
                var selectJobs = CassetteMaps.FindAll(x => x.IsSelected);
                foreach (var item in selectJobs)
                {
                    item.PPID = selectedPPID;
                }
            }
        }

        private List<string> ppids;
        /// <summary>
        /// 界面 PPID 绑定列表
        /// </summary>
        public List<string> PPIDs
        {
            get { return ppids; }
            set
            {
                ppids = value;
                RaisePropertyChanged(nameof(PPIDs));
            }
        }

        private List<JobModel> cassetteMaps;
        /// <summary>
        /// 所有层的玻璃信息
        /// </summary>
        public List<JobModel> CassetteMaps
        {
            get { return cassetteMaps; }
            set
            {
                cassetteMaps = value;
                RaisePropertyChanged(nameof(CassetteMaps));
            }
        }


        #endregion

        #region 命令

        private DelegateCommand downLoadCommand;
        /// <summary>
        /// DownLoad 按钮命令
        /// </summary>
        public DelegateCommand DownLoadCommand
        {
            get { return downLoadCommand ?? new DelegateCommand(DownLoadFunction); }
        }

        private DelegateCommand cancelCommand;
        /// <summary>
        /// Cancel 按钮命令
        /// </summary>
        public DelegateCommand CancelCommand
        {
            get { return cancelCommand ?? new DelegateCommand(CancelFunction); }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 初始化
        /// </summary>
        private async void Init()
        {
            List<JobModel> cassetteMap = new List<JobModel>();
            CassetteMaps = new List<JobModel>();
            char[] slotMap = Port.SlotMap.ToCharArray();
            for (int i = 0; i < 30; i++)
            {
                JobModel job = new JobModel();
                if (slotMap[i] == '1')
                {
                    job.IsHasGlass =true;
                    job.IsSelected = true;
                    job.SlotNo = i + 1;
                    job.ProductId = port.LotId + (i+1).ToString().PadLeft(2,'0');
                    job.LotId = port.LotId;
                    job.PPID = "CIM_TEST";
                    job.Judge = "G";
                    job.JobStatus = JobState.Selected;
                    job.WorkOrder = "Admin";
                    job.Category = "EN";
                    job.ProductSpec = "TEST";
                    job.GlassType = "ArrayGlass";
                    job.ProductType = Productype.MQC;
                    job.Thinkness = "0.5";
                    job.ProductSize = "1800*925";
                    job.OperationId = "Oper01";
                    job.ProductSpecName = "TEST01";
                    job.ProductFlowName = "TEST01";
                }
                else
                {
                    job.IsHasGlass = false;
                    job.IsSelected = false;
                    job.SlotNo = i + 1;
                    job.JobStatus = JobState.Queued;
                }
                cassetteMap.Add(job);
            }
            cassetteMaps = cassetteMap.OrderByDescending(p => p.SlotNo).ToList();

            //调用API
            HttpRequest request = new HttpRequest();
            request.Route = "ProcessProgram/GetProcessPrograms";
            RequestResult result = await _httpRequest.SendGetAsync(request);
            var processPrograms = JsonConvert.DeserializeObject<List<ProceeProgramClientDto>>(Convert.ToString(result.Data));
            if (processPrograms != null)
            {
                foreach (var item in processPrograms)
                {
                    PPIDs.Add(item.PPID);
                }
            }

            foreach(var item in CassetteMaps)
            {
                item.PPIDList = PPIDs;
            }
        }

        /// <summary>
        /// 获取选中的层的玻璃信息
        /// </summary>
        private void GetSelectSlot()
        {
            JobModel? selectJob = CassetteMaps.FirstOrDefault(j => j.SlotNo == SelectSlot.SlotNo);
            //if (selectJob != null)
            //{
            //    selectJob.IsSelected = true;
            //}
        }

        /// <summary>
        /// DownLoad 按钮命令执行逻辑
        /// </summary>
        private void DownLoadFunction()
        {
            var selectedMaps = CassetteMaps.FindAll(j=>j.IsSelected);
            DialogParameters paras = new DialogParameters()
            {
                {"Maps", selectedMaps}
            };
            _dialogService.ShowDialog("DoweLoadView", paras, (r) =>
            {
                if(r.Result == ButtonResult.OK)
                {
                    SendCassetteMapDownLoad();
                }
            });
        }

        private async void SendCassetteMapDownLoad()
        {
            HttpRequest request = new HttpRequest();
            request.Route = "Port/SendCassetteMapDownLoadCommand";
            CassetteMapDownLoadClientDto dto = new CassetteMapDownLoadClientDto();
            dto.PortId = Port.PortId;
            dto.LotId = Port.LotId;
            dto.PPID = SelectedPPID;
            dto.ProductType = PortProductType.MQC;
            foreach(var item in CassetteMaps)
            {
                if (item.IsHasGlass)
                {
                    JobInfoClientDto jobInfo = new JobInfoClientDto();
                    jobInfo.LotId = item.LotId;
                    jobInfo.ProductSize = item.ProductSize;
                    jobInfo.JobId = item.ProductId;
                    //jobInfoty.GlassType = item.GlassType;
                    jobInfo.CassetteSequenceNo = Port.CassetteSequenceNo;
                    jobInfo.SlotSequenceNo = item.SlotNo;
                    jobInfo.GlassCode = GetGlassCode(Port.CassetteSequenceNo, item.SlotNo);
                    //jobInfoty.ProductCategory = item.ProductCategory;
                    //jobInfoty.ProductCategory = item.ProductCategory;
                    jobInfo.Judge = item.Judge;
                    jobInfo.PPID = item.PPID;
                    //jobInfoty.Grade = item.Grade;
                    jobInfo.Status = item.JobStatus;
                    jobInfo.ProductType = item.ProductType;
                    jobInfo.SlotState = item.SlotState;
                    jobInfo.Thickness = item.Thinkness;
                    jobInfo.WorkOrder = item.WorkOrder;
                    dto.JobInfos.Add(jobInfo);
                }                
            }
            request.Parameters = JsonConvert.SerializeObject(dto);
            RequestResult result = await _httpRequest.SendPostAsync(request);
            if (result.IsSuccess)
            {
                var reply = JsonConvert.DeserializeObject<CassetteMapDownLoadClientDto>(result.Data.ToString());
                //MessageBox.Show("设备回复   " + reply..ToString());
            }
            else
            {
                //MessageBox.Show("Server Is Busy");
            }
            SuccessFunction();
        }

        /// <summary>
        /// 下账成功后执行逻辑
        /// </summary>
        private void SuccessFunction()
        {
            DialogResult dialogResult = new DialogResult(ButtonResult.OK);
            this.RequestClose.Invoke(dialogResult);
        }

        /// <summary>
        /// Cancel 按钮命令执行逻辑
        /// </summary>
        private void CancelFunction()
        {            
            DialogResult dialogResult = new DialogResult(ButtonResult.Cancel);
            this.RequestClose.Invoke(dialogResult);
        }

        private string GetGlassCode(int cstSeqNo,int slotNo)
        {
            string strA = cstSeqNo.ToString();
            string strB = (slotNo.ToString()).PadLeft(2,'0');
            return string.Concat(strA, strB);
        }

        #endregion



        #region IDialogAware 相关
        public string Title { get; set; } = "Cassette Map DownLoad";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            var paras = parameters.GetValue<PortModel>("SelectPort");
            if (paras != null)
            {
                Port = paras;
                Init();
            }
        }
        #endregion

    }
}
